#include "LineEdit.h"
#include "../../ImageManager.h"

namespace PickinOpenSticks {
    namespace Ui {

        void LineEdit::Draw(sf::RenderTarget* target) {
            if (!visible) return;
            target->Draw(sprite);
            target->Draw(text);
        }

        void LineEdit::SetDefaultImage() {
            sf::Image img;
            img.Create(100, 50, sf::Color(255, 255, 255));
            sprite.SetImage(ImageManager::GetSingleton().GetImage(img, "basic_line_edit"));
            pos.Setup(0, 0, sprite.GetImage()->GetWidth(), sprite.GetImage()->GetHeight());
            sprite.SetPosition(0, 0);
        }

        void LineEdit::SetPos(int x, int y) {
            pos.x = x;
            pos.y = y;
            sprite.SetPosition((float) x, (float) y);
            text.SetPosition((float) x + 5, (float) y + pos.h / 2 - text.GetSize() / 2);
        }

        void LineEdit::OnKeyPressed(sf::Event *event) {
            if (event->Key.Code == sf::Key::Back) {
                cout << "Backspace pressed!" << endl;
                std::string sText = text.GetText();
                //erase last character
                sText = sText.substr(0, sText.size() - 1);
                text.SetText(sText);
            }
        }

        void LineEdit::OnTextEntered(sf::Event* event) {
            std::string sText = text.GetText();
            std::string old = sText;
            sText += event->Text.Unicode;
            text.SetText(sText);
            if (text.GetRect().GetWidth() > sprite.GetSize().x)
                text.SetText(old);

            //backspace pressed ?
            if (event->Text.Unicode == 8) {
                cout << "Backspace pressed!" << endl;
                std::string sText = text.GetText();
                //erase last character
                sText = sText.substr(0, sText.size() - 2);
                text.SetText(sText);
            }
        }

    }
}
